import axios from 'axios'
import { Toast } from 'vant'
import { getToken, removeToken } from '@/utils/auth'
import router from '@/router'
import qs from 'qs'

const service = axios.create({
  // baseURL: 'http://ith5.chinalife-p.com.cn/', 
  baseURL: 'http://192.168.1.34:80/',
  // baseURL: 'http://192.168.1.194/',
})

// request interceptor
service.interceptors.request.use(
  config => {
    config.headers['Authorization'] = getToken();
    if(config.method === 'post'){
      config.data = qs.stringify(config.data)
    }
    return config;
  },
  error => {
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  response => {
    const res = response.data
    // if the custom code is not 20000, it is judged as an error.
    if (res.code !== 200) {
      if (res.code === 401) {
        Toast('登录过期，请重新登录')
        removeToken()
        router.push('/login')
      } else  {
        //暂时避免首页提示对象不存在
        if( res.message.indexOf('non-object') == -1){
          Toast(res.message)
        }
        return Promise.reject(new Error(res.message || 'Error'))
      }
    } else {
      return res
    }
  },
  error => {
    Toast(error.message)
    return Promise.reject(error)
  }
)



export default service
